package com.yh.supergo.sso.service.impl;

import com.yh.supergo.http.HttpResult;
import com.yh.supergo.pojo.User;
import com.yh.supergo.service.base.impl.BaseServiceImpl;
import com.yh.supergo.user.pojo.UserInfo;
import com.yh.supergo.sso.service.UserService;
import com.yh.supergo.user.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Description Service
 * @Author 0715-YuHao
 * @Date 2020/11/25 16:54
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public HttpResult doLogin(UserInfo userInfo) {
        //根据用户名查询用户信息
        User query = new User();
        query.setUsername(userInfo.getUsername());
        List<User> list = this.findByWhere(query);
        //如果没有结果说明用户不存在，返回失败
        if (list == null || list.size() == 0) {
            return HttpResult.error(401, "用户名或密码错误");
        }
        //如果有结果，判断密码是否正确
        User user = list.get(0);
        //如果密码不正确返回失败
        if (!BCrypt.checkpw(userInfo.getPassword(), user.getPassword())) {
            return HttpResult.error(401, "用户名或密码错误");
        }
        //如果密码正确，登录成功。
        userInfo.setId(user.getId());
        //生成token并返回
        String token = jwtUtil.generateToken(userInfo);
        return HttpResult.ok(token);
    }
}
